package org.shuma.user.mng.handler;

import org.shuma.user.utils.HttpCodeEnum;
import org.shuma.user.utils.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

/**
 * spring统一异常处理
 * 将异常信息封装成JSON返回给前端
 *
 * @author zhao haitao
 * @date 2024/06/17 1:46 PM
 */
@RestControllerAdvice
//@ControllerAdvice
public class ValidParamExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
//    @ResponseBody
    public Result<String> methodArgumentNotValidException(ConstraintViolationException e) {
        Result<String> result = new Result<>();
        result.error(HttpCodeEnum.PARAMS_ERROR, e.getMessage().split(": ")[1]);
        return result;
    }

    @ExceptionHandler(BindException.class)
//    @ResponseBody
    public Result<String> BindExceptionHandler(BindException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        List<String> msgList = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            msgList.add(allError.getDefaultMessage());
        }
        Result<String> result = new Result<>();
        result.error(HttpCodeEnum.PARAMS_ERROR, msgList.toString());
        return result;
    }
}